import React, { Component } from 'react';
import { Form, Row, Col } from 'antd';
import { connect } from 'dva';
import {
  BaseInput,
  RangeInputNumber,
  BaseRangePicker,
  BaseSelect,
  InquiryAreaButton,
} from '@/components';
import { ObjectType, getRangePickerTime } from '../../../utils';
import { examineStatus, approveType, userTypes, accountType, changeTypes } from '@/const/risk';
import { getSubTypeData } from '../../methods';

const style = require('./form.less');

interface SearchConditionState {
  errorTip: string;
  showErrorTip: boolean;
  maxAmount: undefined | number;
  minAmount: undefined | number;
  selectedUserType: number;
  subTypeData: ObjectType;
}

class SearchCondition extends Component<ObjectType, SearchConditionState> {
  constructor(props: ObjectType) {
    super(props);
    this.state = {
      errorTip: '起始金额必须小于结束金额',
      showErrorTip: false,
      maxAmount: undefined,
      minAmount: undefined,
      subTypeData: getSubTypeData(1009), // 细分类型，根据调整类型显示子项发生变化,
    };
  }

  componentDidMount() {
    const {
      formData: { inquiryValues, inquiryCondition, subTypeData },
      tableData: { currentPage },
      form,
    } = this.props;
    const attrs = Object.keys(inquiryValues);
    attrs.forEach((val: string) => {
      form.setFieldsValue({
        [val]: inquiryValues[val],
      });
    });

    if (Object.keys(subTypeData).length) {
      this.setState({
        subTypeData,
      });
    }

    if (Object.keys(inquiryCondition).length) {
      this.handleGetTableList(inquiryCondition, currentPage);
    }
  }

  // 查询渲染表格的数据
  handleGetTableList = (condition: ObjectType, page = 1) => {
    const {
      dispatch,
      tableData: { pageSize },
    } = this.props;
    // eslint-disable-next-line no-restricted-syntax
    for (const attr in condition) {
      if (condition.hasOwnProperty(attr) && !condition[attr]) {
        // eslint-disable-next-line no-param-reassign
        delete condition[attr];
      }
    }
    dispatch({
      type: 'financeAdjustmentExamine/getUserRiskDataEffect',
      payload: {
        ...condition,
        page,
        size: pageSize,
      },
    });
  };

  /**
   * 获取审核状态
   * @param selectItem 选中的文字
   * @param arr 渲染的数据，array
   * @param hasAll 数据里是否包含全部
   * @return id string  获取选项的id或者id集合用逗号连接
   */
  getId = (selectItem: string | undefined, arr, hasAll: boolean) => {
    let id = '';
    if (selectItem) {
      if (selectItem === '全部' && !hasAll) {
        const ids = arr.map((val: ObjectType) => val.id);
        ids.shift();
        id = ids.join(',');
      } else {
        id = `${arr.filter((val: ObjectType) => val.text === selectItem)[0].id}`;
      }
    }
    return id;
  };

  // 点击表单区的查询
  handleSubmit = (e: ObjectType) => {
    e.preventDefault();
    const { form, dispatch } = this.props;
    form.validateFields((err: null | ObjectType, values: ObjectType) => {
      if (!err) {
        const { subTypeData } = this.state;

        const {
          subType,
          status,
          changeType,
          userType,
          username,
          minAmount,
          maxAmount,
          keywords,
          creator,
          firstApprover,
          secondApprover,
        } = values;
        const rangeTime = getRangePickerTime(values);
        // 查询用户风险名单
        const condition = {
          username,
          startDate: rangeTime[0], // 开始日期
          endDate: rangeTime[1], // 结束日期
          minAmount, // 调整金额最小值
          maxAmount, // 调整金额最大值
          userType: this.getId(userType, userTypes, true), // 账户类型
          keywords, // 账户名
          changeType: this.getId(changeType, changeTypes), // 操作类型【调整类型】
          creator, // 申请人
          firstApprover, // 一审人
          secondApprover, // 二审人
          status: this.getId(status, examineStatus, true), // 审核状态
          subType: this.getId(subType, subTypeData), // 细分类型
        };

        // 查询渲染表格的数据
        this.handleGetTableList(condition);

        dispatch({
          type: 'financeAdjustmentExamine/setFormAreaInfo',
          payload: {
            subTypeData,
            inquiryValues: values,
            inquiryCondition: condition,
          },
        });
      }
    });
  };

  // 调整金额第一个输入框
  onStartChange = (e: string) => {
    const { maxAmount } = this.state;
    const minAmount = Number(e);
    let rule = maxAmount < minAmount;
    if (maxAmount === 0 || minAmount === 0) rule = false;
    this.switchShowErrorTip(rule, 'minAmount', minAmount);
  };

  // 调整金额第二个输入框
  onEndChange = (e: number) => {
    const { minAmount } = this.state;
    const maxAmount = Number(e);
    let rule = minAmount > maxAmount;
    if (maxAmount === 0 || minAmount === 0) rule = false;
    this.switchShowErrorTip(rule, 'maxAmount', maxAmount);
  };

  switchShowErrorTip = (b: boolean, id: string, value: number | undefined) => {
    if (b) {
      this.setState(
        {
          showErrorTip: true,
        },
        () => {
          this.props.form.setFieldsValue({
            [id]: 0,
          });
        },
      );
    } else {
      this.setState({
        showErrorTip: false,
        [id]: value,
      });
    }
  };

  // 调整类型选择
  onChangeTypesHandle = (value, option) => {
    const { key } = option;
    const currentId = Number(key);
    this.setState({
      subTypeData: getSubTypeData(currentId),
    });
  };

  handleResetCallBack = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'financeAdjustmentExamine/setPageSize',
      payload: {
        currentPage: 1,
      },
    });
    this.setState({
      subTypeData: getSubTypeData(1009),
    });
    const defaultInquiryCondition = {
      startDate: getRangePickerTime()[0], // 开始日期
      endDate: getRangePickerTime()[1], // 结束日期
      userType: -1, // 账户类型
      changeType: 1009, // 操作类型【调整类型】
      status: -1, // 审核状态
      subType: '1,2', // 细分类型
    };
    this.handleGetTableList(defaultInquiryCondition);
  };

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { maxAmountDisabled, errorTip, showErrorTip, subTypeData } = this.state;

    return (
      <Form className={style.searchConditionWrap} labelAlign="left" onSubmit={this.handleSubmit}>
        <Row gutter={12}>
          <Col span={7}>
            <BaseRangePicker
              getFieldDecorator={getFieldDecorator}
              id="select-date"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 28 }}
            />
          </Col>
          <Col span={5}>
            <RangeInputNumber
              getFieldDecorator={getFieldDecorator}
              label="调整金额"
              startId="minAmount"
              endId="maxAmount"
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 8 }}
              maxAmountDisabled={maxAmountDisabled}
              errorTip={errorTip}
              showErrorTip={showErrorTip}
              onStartChange={this.onStartChange}
              onEndChange={this.onEndChange}
            />
          </Col>
          <Col span={3}>
            <BaseSelect
              label="账户类型"
              getFieldDecorator={getFieldDecorator}
              id="userType"
              optionsData={userTypes}
              OptionKeyAttr="id"
              OptionValueAttr="text"
              OptionTextAttr="text"
              initialValue="全部"
            />
          </Col>

          <Col span={3}>
            <BaseSelect
              label="审查状态"
              getFieldDecorator={getFieldDecorator}
              id="status"
              optionsData={examineStatus}
              OptionKeyAttr="id"
              OptionValueAttr="text"
              OptionTextAttr="text"
            />
          </Col>
        </Row>

        <Row gutter={12}>
          <Col span={4}>
            <BaseSelect
              label="调整类型"
              getFieldDecorator={getFieldDecorator}
              id="changeType"
              optionsData={changeTypes}
              OptionKeyAttr="id"
              OptionValueAttr="text"
              OptionTextAttr="text"
              labelCol={{ span: 7 }}
              wrapperCol={{ span: 7 }}
              onChange={this.onChangeTypesHandle}
              initialValue="加币-计入红利"
            />
          </Col>

          <Col span={4}>
            <BaseSelect
              label="细分类型"
              getFieldDecorator={getFieldDecorator}
              id="subType"
              optionsData={subTypeData}
              OptionKeyAttr="id"
              OptionValueAttr="text"
              OptionTextAttr="text"
              labelCol={{ span: 7 }}
              wrapperCol={{ span: 7 }}
              initialValue="全部"
            />
          </Col>

          <Col span={5}>
            <BaseInput<>
              trigger={['click']}
              menuData={accountType}
              buttonText="账号名"
              getFieldDecorator={getFieldDecorator}
              getFieldDecoratorId="keywords"
              placeholder="请输入"
              autoComplete="off"
              needChangeId // 点击menu的时候改变这个项的id
              dropDownLabel
            />
          </Col>

          <Col span={5}>
            <BaseInput<>
              trigger={['click']}
              menuData={approveType}
              buttonText="二审人"
              getFieldDecorator={getFieldDecorator}
              getFieldDecoratorId="secondApprover"
              placeholder="请输入"
              autoComplete="off"
              needChangeId // 点击menu的时候改变这个项的id
              dropDownLabel
            />
          </Col>
        </Row>
        <Row>
          <InquiryAreaButton
            className={style.inquiryBtn}
            form={this.props.form}
            handleResetCallBack={this.handleResetCallBack}
          />
        </Row>
      </Form>
    );
  }
}

function mapStateToProps({
  financeAdjustmentExamine: { tableData, formData },
}: {
  financeAdjustmentExamine: ObjectType;
}) {
  return { tableData, formData };
}
export default connect(mapStateToProps)(Form.create()(SearchCondition));
